'
' DotNetNuke -  http://www.dotnetnuke.com
' Copyright (c) 2002-2005
' by Shaun Walker ( sales@perpetualmotion.ca ) of Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
'
Imports DotNetNuke
Imports System.Web.UI.WebControls
Imports DotNetNuke.UI.UserControls

Namespace DotNetNuke.Modules.ProjectTracker

    ''' -----------------------------------------------------------------------------
    ''' <summary>
    ''' The EditPT_States PortalModuleBase is used to manage PT_States
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks>
    ''' </remarks>
    ''' <history>
    ''' </history>
    ''' -----------------------------------------------------------------------------
    Public MustInherit Class WorkflowStatesEdit
        Inherits Entities.Modules.PortalModuleBase
        Const INT_SUBSCRIBERS As Integer = 1
        Const INT_AUTHORIZED As Integer = 2

#Region "Controls"

        Protected WithEvents fldStateName As TextBox  ' nvarchar
        Protected WithEvents fldDescription As TextBox  ' ntext
        Protected WithEvents fldNotes As TextBox  ' ntext

        Protected WithEvents rfvStateName As RequiredFieldValidator
        Protected WithEvents rfvDescription As RequiredFieldValidator
        Protected WithEvents myExitCriteriaGrid As DataGrid

        Protected WithEvents ddlStatus As DropDownList

        Protected WithEvents ddlNonSubscribers As ListBox
        Protected WithEvents btnAddSubscriber As Button
        Protected WithEvents btnDelSubscriber As Button
        Protected WithEvents ddlSubscribers As ListBox

        Protected WithEvents ddlAuthorized As ListBox
        Protected WithEvents ddlNonAuthorized As ListBox
        Protected WithEvents btnAddAuthorized As Button
        Protected WithEvents btnDelAuthorized As Button

        Protected WithEvents cmdUpdate As LinkButton
        Protected WithEvents cmdCancel As LinkButton
        Protected WithEvents cmdDelete As LinkButton

        Protected WithEvents rfvNotes As RequiredFieldValidator
        Protected WithEvents fldEntrySubject As TextBox
        Protected WithEvents fldEntryBody As TextBox
        Protected WithEvents fldPassSubject As TextBox
        Protected WithEvents fldPassBody As TextBox
        Protected WithEvents fldFailSubject As TextBox
        Protected WithEvents fldFailBody As TextBox

        Protected WithEvents lbAddCriteria As LinkButton

        Protected WithEvents subEMails As System.Web.UI.WebControls.DataGrid
        Protected WithEvents lbAddSubEMail As System.Web.UI.WebControls.LinkButton
        Protected WithEvents lbAddAuthEMail As System.Web.UI.WebControls.LinkButton
        Protected WithEvents authEMails As System.Web.UI.WebControls.DataGrid
        Protected WithEvents lbAuthEMails As System.Web.UI.WebControls.LinkButton
        Protected WithEvents lbNonDownload As System.Web.UI.WebControls.ListBox
        Protected WithEvents btnAddDownload As System.Web.UI.WebControls.Button
        Protected WithEvents bntDelDownload As System.Web.UI.WebControls.Button
        Protected WithEvents lbDownload As System.Web.UI.WebControls.ListBox
        Protected WithEvents lbNonComment As System.Web.UI.WebControls.ListBox
        Protected WithEvents btnAddComment As System.Web.UI.WebControls.Button
        Protected WithEvents btnDelComment As System.Web.UI.WebControls.Button
        Protected WithEvents lbComment As System.Web.UI.WebControls.ListBox

        ' footer
        Protected WithEvents ctlAudit As ModuleAuditControl

#End Region

#Region "Private Members"

        Private m_itemId As Integer = -1
        Private m_moduleId As Integer = -1

        Private m_StatesController As New DotNetNuke.Modules.ProjectTracker.StatesController
        Private m_StatesInfo As DotNetNuke.Modules.ProjectTracker.StatesInfo

#End Region

#Region "Private Functions"

        Private Function SaveData() As Integer
            Dim newID As Integer = -1
            Dim authorizedRoles As String
            Dim subscriberRoles As String
            Dim downloadRoles As String
            Dim commentRoles As String

            Try
                ' Only Update if Entered data is Valid
                If Page.IsValid = True Then

                    ' /// Create an instance of the Event DB component
                    If m_itemId = -1 Then
                        m_StatesInfo = New StatesInfo
                        m_StatesInfo.ItemID = m_itemId
                    Else
                        m_StatesInfo = m_StatesController.GetStatesInfo(m_itemId)
                    End If
                    m_StatesInfo.ModuleID = m_moduleId
                    m_StatesInfo.CreatedByUser = UserInfo.UserID
                    m_StatesInfo.CreatedDate = Date.Now()
                    m_StatesInfo.StateName = fldStateName.Text.Trim()
                    m_StatesInfo.Description = fldDescription.Text.Trim()
                    m_StatesInfo.Status = Integer.Parse(ddlStatus.SelectedValue)

                    subscriberRoles = ";"
                    authorizedRoles = ";"
                    downloadRoles = ";"
                    commentRoles = ";"

                    For Each item As ListItem In ddlSubscribers.Items
                        subscriberRoles &= (item.Value & ";")
                    Next
                    For Each item As ListItem In ddlAuthorized.Items
                        authorizedRoles &= (item.Value & ";")
                    Next
                    For Each item As ListItem In lbDownload.Items
                        downloadRoles &= (item.Value & ";")
                    Next
                    For Each item As ListItem In lbComment.Items
                        commentRoles &= (item.Value & ";")
                    Next

                    If subscriberRoles.Length = 1 Then subscriberRoles = ""
                    If authorizedRoles.Length = 1 Then authorizedRoles = ""
                    If downloadRoles.Length = 1 Then downloadRoles = ""
                    If commentRoles.Length = 1 Then commentRoles = ""

                    m_StatesInfo.SubscriberRoles = subscriberRoles
                    m_StatesInfo.AuthorizedRoles = authorizedRoles
                    m_StatesInfo.DownloadRoles = downloadRoles
                    m_StatesInfo.CommentRoles = commentRoles

                    m_StatesInfo.Notes = fldNotes.Text.Trim()

                    m_StatesInfo.EntryBody = fldEntryBody.Text.Trim()
                    m_StatesInfo.EntrySubject = fldEntrySubject.Text.Trim()
                    m_StatesInfo.FailSubject = fldFailSubject.Text.Trim()
                    m_StatesInfo.FailBody = fldFailBody.Text.Trim()
                    m_StatesInfo.PassSubject = fldPassSubject.Text.Trim()
                    m_StatesInfo.PassBody = fldPassBody.Text.Trim()

                    ' /// if ItemId is 0 then we're adding a new item, otherwise we're updating an existing item
                    If m_itemId = -1 Then
                        ' /// get the last process value and increment it to place this new item
                        ' /// at the end of the list
                        Try
                            Dim steps As ArrayList = m_StatesController.GetStatesList(ModuleId)
                            Dim lastStep As DotNetNuke.Modules.ProjectTracker.StatesInfo
                            lastStep = CType(steps(steps.Count - 1), DotNetNuke.Modules.ProjectTracker.StatesInfo)
                            m_StatesInfo.ProcessOrder = lastStep.ProcessOrder + 1
                        Catch ex As Exception
                            m_StatesInfo.ProcessOrder = 1
                        End Try
                        newID = m_StatesController.AddStates(m_StatesInfo)
                    Else
                        m_StatesController.UpdateStates(m_StatesInfo)
                        newID = m_itemId
                    End If

                    Return newID

                Else

                    Return -1

                End If

            Catch exc As Exception    'Module failed to load

                ProcessModuleLoadException(Me, exc)

            End Try
        End Function

#End Region

#Region "Event Handlers"

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Page_Load runs when the control is loaded
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim item As ListItem
            Try
                ' Determine ItemId of PT_States to Update
                If Not (Request.QueryString("ItemId") Is Nothing) Then
                    m_itemId = Int32.Parse(Request.QueryString("ItemId"))
                End If

                ' /// Determine ModuleId
                m_moduleId = Int32.Parse(Request.Params("Mid"))

                m_StatesInfo = Nothing

                ddlStatus.Items.Clear()
                ddlStatus.Items.Add(New ListItem("Active", "1"))
                ddlStatus.Items.Add(New ListItem("InActive", "0"))

                ' If the page is being requested the first time, determine if an
                ' PT_States itemId value is specified, and if so populate page
                ' contents with the PT_States details
                If Page.IsPostBack = False Then

                    cmdDelete.Attributes.Add("onClick", "javascript:return confirm('" & Localization.GetString("DeleteItem") & "');")

                    If m_itemId <> -1 Then
                        ' Obtain a single row of PT_States information
                        ' /// Retrieve the requested Item using the ItemId
                        m_StatesInfo = m_StatesController.GetStatesInfo(m_itemId)

                        If Not m_StatesInfo Is Nothing Then
                            fldStateName.Text = m_StatesInfo.StateName.ToString()
                            fldDescription.Text = m_StatesInfo.Description.ToString()
                            ddlStatus.SelectedValue = m_StatesInfo.Status.ToString()
                            fldNotes.Text = m_StatesInfo.Notes.ToString()
                            fldEntrySubject.Text = m_StatesInfo.EntrySubject.ToString()
                            fldEntryBody.Text = m_StatesInfo.EntryBody.ToString()
                            fldPassSubject.Text = m_StatesInfo.PassSubject.ToString()
                            fldPassBody.Text = m_StatesInfo.PassBody.ToString()
                            fldFailSubject.Text = m_StatesInfo.FailSubject.ToString()
                            fldFailBody.Text = m_StatesInfo.FailBody.ToString()
                            ctlAudit.CreatedDate = m_StatesInfo.CreatedDate.ToString
                            ctlAudit.CreatedByUser = m_StatesInfo.CreatedByUser.ToString

                        Else       ' security violation attempt to access item not related to this Module

                            Response.Redirect(NavigateURL(), True)
                        End If

                        ''' bind the exit criteria grid
                        Dim _exitCriteriaController As New ExitCriteriaController
                        Localization.LocalizeDataGrid(myExitCriteriaGrid, Me.LocalResourceFile)
                        myExitCriteriaGrid.DataSource = _exitCriteriaController.GetExitCriteriaList(m_itemId)
                        myExitCriteriaGrid.DataBind()

                    Else

                        fldEntrySubject.Text = ""
                        fldEntryBody.Text = ""
                        fldPassSubject.Text = ""
                        fldPassBody.Text = ""
                        fldFailSubject.Text = ""
                        fldFailBody.Text = ""
                        cmdDelete.Visible = False
                        ctlAudit.Visible = False

                    End If

                    ''' bind the 2 role double-grids
                    ddlNonSubscribers.Items.Clear()
                    ddlSubscribers.Items.Clear()
                    ddlNonAuthorized.Items.Clear()
                    ddlAuthorized.Items.Clear()

                    ''' bind the download and comment roles
                    lbNonDownload.Items.Clear()
                    lbDownload.Items.Clear()
                    lbNonComment.Items.Clear()
                    lbComment.Items.Clear()

                    ''' bind the email grids
                    Dim subscribersController As New StateSubscribersController
                    subEMails.DataSource = subscribersController.GetStateSubscribersList(m_itemId, INT_SUBSCRIBERS)
                    subEMails.DataBind()

                    authEMails.DataSource = subscribersController.GetStateSubscribersList(m_itemId, INT_AUTHORIZED)
                    authEMails.DataBind()

                    Dim objRoles As New DotNetNuke.Security.Roles.RoleController
                    Dim roles As ArrayList = objRoles.GetPortalRoles(PortalId)
                    For Each role As DotNetNuke.Security.Roles.RoleInfo In roles
                        item = New ListItem
                        item.Text = role.RoleName
                        item.Value = role.RoleID.ToString()
                        '''
                        If m_StatesInfo Is Nothing Then
                            ddlNonSubscribers.Items.Add(item)
                            ddlNonAuthorized.Items.Add(item)
                            lbNonDownload.Items.Add(item)
                            lbNonComment.Items.Add(item)
                        Else
                            If m_StatesInfo.SubscriberRoles.IndexOf(";" & item.Value & ";") < 0 Then
                                ddlNonSubscribers.Items.Add(item)
                            Else
                                ddlSubscribers.Items.Add(item)
                            End If
                            '''
                            If m_StatesInfo.AuthorizedRoles.IndexOf(";" & item.Value & ";") < 0 Then
                                ddlNonAuthorized.Items.Add(item)
                            Else
                                ddlAuthorized.Items.Add(item)
                            End If
                            '''
                            If m_StatesInfo.DownloadRoles.IndexOf(";" & item.Value & ";") < 0 Then
                                lbNonDownload.Items.Add(item)
                            Else
                                lbDownload.Items.Add(item)
                            End If
                            '''
                            If m_StatesInfo.CommentRoles.IndexOf(";" & item.Value & ";") < 0 Then
                                lbNonComment.Items.Add(item)
                            Else
                                lbComment.Items.Add(item)
                            End If
                        End If
                    Next

                End If
            Catch exc As Exception    'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' cmdCancel_Click runs when the cancel button is clicked
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub cmdCancel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdCancel.Click
            Try
                Response.Redirect(EditUrl("Setup"), True)
            Catch exc As Exception    'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' cmdDelete_Click runs when the delete button is clicked
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub cmdDelete_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdDelete.Click
            Try
                If m_itemId <> -1 Then
                    m_StatesController.DeleteStates(m_itemId)
                End If

                ' Redirect back to the portal home page
                Response.Redirect(EditUrl("Setup"), True)
            Catch exc As Exception    'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' cmdUpdate_Click runs when the update button is clicked
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub cmdUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdUpdate.Click
            If SaveData() > -1 Then
                ' Redirect back to the portal home page
                Response.Redirect(EditUrl("Setup"), True)
            End If
        End Sub

        Private Sub myExitCriteriaGrid_ItemDataBound(ByVal sender As Object, ByVal e As DataGridItemEventArgs) Handles myExitCriteriaGrid.ItemDataBound
            If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
                '' build the edit navigation url
                Dim hyp As HyperLink = CType(e.Item.Cells(0).FindControl("hlEdit"), HyperLink)
                If Not hyp Is Nothing Then
                    hyp.NavigateUrl = EditUrl("ItemID", e.Item.Cells(1).Text, "EditExitCriteria", "")
                End If
            End If
        End Sub

        Private Sub btnAddSubscriber_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddSubscriber.Click
            TransferListItems(ddlNonSubscribers, ddlSubscribers)
        End Sub

        Private Sub btnDelSubscriber_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelSubscriber.Click
            TransferListItems(ddlSubscribers, ddlNonSubscribers)
        End Sub

        Private Sub btnAddAuthorized_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddAuthorized.Click
            TransferListItems(ddlNonAuthorized, ddlAuthorized)
        End Sub

        Private Sub btnDelAuthorized_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelAuthorized.Click
            TransferListItems(ddlAuthorized, ddlNonAuthorized)
        End Sub

        Private Sub btnAddDownload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddDownload.Click
            TransferListItems(lbNonDownload, lbDownload)
        End Sub

        Private Sub bntDelDownload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles bntDelDownload.Click
            TransferListItems(lbDownload, lbNonDownload)
        End Sub

        Private Sub btnAddComment_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddComment.Click
            TransferListItems(lbNonComment, lbComment)
        End Sub

        Private Sub btnDelComment_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelComment.Click
            TransferListItems(lbComment, lbNonComment)
        End Sub

        Private Sub TransferListItems(ByVal lb1 As ListBox, ByVal lb2 As ListBox)
            Dim i As Integer
            Dim item As ListItem
            For i = lb1.Items.Count - 1 To 0 Step -1
                item = lb1.Items(i)
                If item.Selected Then
                    lb2.Items.Add(item)
                    lb1.Items.Remove(item)
                End If
            Next
            lb1.SelectedIndex = -1
            lb2.SelectedIndex = -1
        End Sub

        Private Sub lbAddCriteria_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lbAddCriteria.Click
            ' /// if we haven't saved yet .. save the workflow state
            Dim newID As Integer
            newID = SaveData()
            If newID > -1 Then
                Response.Redirect(EditUrl("ItemID", "-1", "EditExitCriteria", "StateId=" & newID.ToString()), True)
            End If
        End Sub

        Private Sub lbAddSubEMail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lbAddSubEMail.Click
            ' /// if we haven't saved yet .. save the workflow state
            Dim newID As Integer
            newID = SaveData()
            If newID > -1 Then
                Response.Redirect(EditUrl("ItemID", "-1", "EditSubEMail", "StateId=" & newID.ToString(), "TypeID=1"), True)
            End If
        End Sub

        Private Sub lbAuthEMails_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lbAuthEMails.Click
            ' /// if we haven't saved yet .. save the workflow state
            Dim newID As Integer
            newID = SaveData()
            If newID > -1 Then
                Response.Redirect(EditUrl("ItemID", "-1", "EditAuthEMail", "StateId=" & newID.ToString(), "TypeID=2"), True)
            End If
        End Sub

#End Region

#Region " Web Form Designer Generated Code "

        'This call is required by the Web Form Designer.
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

        End Sub

        Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
            'CODEGEN: This method call is required by the Web Form Designer
            'Do not modify it using the code editor.
            InitializeComponent()
        End Sub

#End Region

        Private Sub subEMails_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles subEMails.ItemDataBound
            If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
                '' build the edit navigation url
                Dim hyp As HyperLink = CType(e.Item.Cells(0).FindControl("hlEdit"), HyperLink)
                If Not hyp Is Nothing Then
                    hyp.NavigateUrl = EditUrl("ItemID", e.Item.Cells(1).Text, "EditSubEMail", "TypeID=1")
                End If
            End If
        End Sub

        Private Sub authEMails_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles authEMails.ItemDataBound
            If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
                '' build the edit navigation url
                Dim hyp As HyperLink = CType(e.Item.Cells(0).FindControl("hlEdit"), HyperLink)
                If Not hyp Is Nothing Then
                    hyp.NavigateUrl = EditUrl("ItemID", e.Item.Cells(1).Text, "EditAuthEMail", "TypeID=2")
                End If
            End If
        End Sub

    End Class

End Namespace
